//
//  ZooSignUpScreen.m
//  ZooNgonDoiOS
//
//  Created by Trung sound on 6/4/12.
//  Copyright (c) 2012 Personal. All rights reserved.
//

#import "ZooSignUpScreen.h"
#import "ValidCore.h"
#import "ZooLoginController.h"
#import "CreateUserTask.h"
#import "RestKit/JSONKit.h"

@implementation ZooSignUpScreen
@synthesize parent = _parent;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        [self setBackgroundColor:[UIColor greenColor]];
        
        _txtUserName = [[UITextField alloc]initWithFrame:CGRectMake(20, 20, 200, 30)];
        _txtPassword = [[UITextField alloc]initWithFrame:CGRectMake(20, 60, 200, 30)];
        _txtPassword.secureTextEntry = YES;
        
        _btnShowPass = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        _btnShowPass.frame = CGRectMake(230, 60, 50, 30);
        [_btnShowPass setTitle:@"show" forState:UIControlStateNormal];
        [_btnShowPass addTarget:self action:@selector(btnShowPassDown) forControlEvents:UIControlEventTouchDown];
        [_btnShowPass addTarget:self action:@selector(btnShowPassUp) forControlEvents:UIControlEventTouchUpInside];
        
        _txtEmail = [[UITextField alloc]initWithFrame:CGRectMake(20, 100, 200, 30)];
        [self addSubview:_txtUserName];
        [self addSubview:_txtPassword];
        [self addSubview:_btnShowPass];
        [self addSubview:_txtEmail];

        [_txtUserName setText:@"123456"];
        [_txtUserName addTarget:self action:@selector(returnClicked) forControlEvents:UIControlEventEditingDidEndOnExit];
        [_txtEmail setText:@"aaaa@aaa.com"];
        
        _btnSignUp = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        _btnSignUp.frame = CGRectMake(20, 140, 100, 50);
        [_btnSignUp setTitle:@"Sign Up" forState:UIControlStateNormal];
        [_btnSignUp addTarget:self action:@selector(btnSignUpClicked) forControlEvents:UIControlEventTouchUpInside];
        
        _btnCancel = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        _btnCancel.frame = CGRectMake(140, 140, 100, 50);
        [_btnCancel setTitle:@"Cancel" forState:UIControlStateNormal];
        [_btnCancel addTarget:self action:@selector(btnCancelClicked) forControlEvents:UIControlEventTouchUpInside];
        
        _activityIndicator = [[LoadingScreenView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
        
        [self addSubview:_btnSignUp];
        [self addSubview:_btnCancel];
        
        _lblWarning = [[UILabel alloc]initWithFrame:CGRectMake(10, 200, 290, 30)];
        _lblWarning.backgroundColor = [UIColor whiteColor];

        [self addSubview:_lblWarning];
        [self addSubview:_activityIndicator];

        _zooSignupResponse = [[ZooSignupResponse alloc]init];

        
    }
    return self;
}

- (void) btnShowPassDown {
    _txtPassword.secureTextEntry = NO;
    [_txtPassword resignFirstResponder];
}

- (void) btnShowPassUp {
    _txtPassword.secureTextEntry = YES;
}

- (void) btnSignUpClicked {
    [self returnClicked];
    BOOL isValidMail;
    isValidMail = [ValidCore checkEmail:_txtEmail.text];

    /*  
        Regular expression for user name: "/^[-a-z0-9_]++$/" && Check text length
        Regular expression for email: "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$"
     */
    if ([ValidCore alpha_dash:_txtUserName.text] && [ValidCore length:_txtUserName.text min:MIN_TEXT_LENGTH max:MAX_TEXT_LENGTH]) {

        if ([ValidCore checkEmail:_txtEmail.text]) {
            [_activityIndicator startAnimating];
            _activityIndicator.hidden = NO;

            CreateUserTask *createUserTask = [[CreateUserTask alloc]initWithParams:_txtUserName.text pass:_txtPassword.text email:_txtEmail.text phone:@"1234567890"];
            [createUserTask doExecute:self];

//            ZooSignUpViewController *zooSignUpViewController = (ZooSignUpViewController *)_parent;
//            [zooSignUpViewController pushToLoginScreen:_txtUserName.text pass:_txtPassword.text];

        } else {
            [self showAlertView:MSG_EMAIL_ERROR];
        }
    } else {

    }
}

- (void) btnCancelClicked {
    [_parent pushToLoginScreen:nil pass:nil];
}

- (void) returnClicked {
    [_txtUserName resignFirstResponder];
    [_txtPassword resignFirstResponder];
    [_txtEmail resignFirstResponder]; 
}

#pragma mark - Control Restkit Delegate

-(void)request:(RKRequest *)request didLoadResponse:(RKResponse *)response{
    NSLog(@"xxxxxxxxxxx %d",[response statusCode]);
    
    NSNumber *aStatus;
    NSNumber *aErrorCode;
    NSString *aError;
    if ([request isPUT]) {
        
        NSString *myJson = [response bodyAsString];
        NSDictionary *parseJSON = [myJson objectFromJSONString];
        aStatus = [parseJSON objectForKey:STATUS]; 
        aErrorCode = [parseJSON objectForKey:ERROR_CODE_RESPONSE]; 
        aError = [parseJSON objectForKey:ERROR_RESPONSE];
        NSLog(@"%@",aStatus);
        
        if ([aStatus isEqualToNumber:[NSNumber numberWithInt:0]]) {
            _zooSignupResponse.status = false;
            _zooSignupResponse.error = [parseJSON objectForKey:ERROR_RESPONSE];
            _zooSignupResponse.errorCode = [parseJSON objectForKey:ERROR_CODE_RESPONSE];
            [_activityIndicator stopAnimating];
            _activityIndicator.hidden = YES;

            if ([aErrorCode isEqualToNumber:[NSNumber numberWithInt:104]]) {
                [self showAlertView:@"username has been exist"];
            } else if ([aErrorCode isEqualToNumber:[NSNumber numberWithInt:108]]) {
                [self showAlertView:@"Email has been exist"];
            }
            
        } else {
            _zooSignupResponse.status = true;
            [_activityIndicator stopAnimating];
            _activityIndicator.hidden = YES;
            [_parent pushToLoginScreen:_txtUserName.text pass:_txtPassword.text];
        }
        
    }
}

- (void)requestDidStartLoad:(RKRequest *)request {
    [_activityIndicator startAnimating];
    _activityIndicator.hidden = NO;
} 

-(void)request:(RKRequest *)request didFailLoadWithError:(NSError *)error{
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"" message:NOT_CONNECT_SERVER delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
    [alertView show];
    [_activityIndicator stopAnimating];
    _activityIndicator.hidden = YES;
}

-(void)showAlertView:(NSString *)pMessage {
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"" message:pMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
    [alertView show];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end
